// pages/product-center/product-center.js
const pageLoad = require('../../behavior/page-load')
const app = getApp()
const {globalData} = app

Component({
  behaviors: [pageLoad],
  options: {
    pureDataPattern: /^_/, // 指定所有 _ 开头的数据字段为纯数据字段
  },
  properties: {
  },
  /**
   * 页面的初始数据
   */
  data: {
    current: 'product',
    open: '',
    merchantList: [],
    showMoreBtn: false,
    bannerList: [],
    typeList: [],
    refreshed: false,
    params: {
      user_merchant_id: '',
      type_belong: '',
      type_tag: ''
    },
    selectOption: {
      typeIndex: -1,
      twoTypeList: []
    },
    _typeIndex: -1,
    cartCount: 0,
    merchant: {},
    show: false
  },
  methods: {
    navToCompanyHandle(event) {
      const {company} = event.currentTarget.dataset
      if (company) {
        wx.navigateTo({
          url: `/pages/company-detail/company-detail?id=${company}`,
        })
      }
    },
    navToMoreHandle(event) {
      wx.navigateTo({
        url: `/pages/company/company?merchant_id=${this.data.params.user_merchant_id}`,
      })
    },
    titleClickHandle() {
      if (!this.data.merchantList || this.data.merchantList.length == 1) {
        return
      }

      this.setData({
        show: true
      })      
    },
    closeHandle() {
      this.setData({
        show: false
      })
    },
    selectHandle(event) {
      const merchant = event.detail
      if (merchant.id == this.data.merchant.id) {
        return;
      }

      this.setData({
        merchant,
        'params.user_merchant_id': merchant.id
      }, () => {
        this.requestBannerList(merchant.id)
        this.requestProductTypeTree(merchant.id)
      })
    },
    // 产品点击
    productTabHandle() {
      const {_typeIndex, typeList} = this.data
      if (! typeList[_typeIndex]) {
        return
      }

      let data = typeList[_typeIndex].childList || []
      let twoTypeList = JSON.parse(JSON.stringify(data))
      this.setData({
        'selectOption.typeIndex': _typeIndex,
        'selectOption.twoTypeList': twoTypeList,
        open: this.data.open == 'product' ? '' : 'product'
      })
    },
    // 装修推荐点击
    recommendTabHandle() {
      this.setData({
        open: this.data.open == 'recommend' ? '' : 'recommend'
      })
    },
    // 遮罩
    maskClickHandle(event) {
      if (event.target.dataset.name === 'mask') {
        this.setData({
          open: ''
        })
      }
    },
    stopTouchMoveHandle() {
      return false
    },
    // 一级类型点击
    typeClickHandle(event) {
      let index = event.currentTarget.dataset.index
      let type = this.data.typeList[index]

      this.setData({
        'selectOption.typeIndex': index,
        'selectOption.twoTypeList': type.childList.map(item => {
          return {
            ...item,
            check: false
          }
        })
      })
    },
    // 二级分类点击
    twoTypeClickHandle(event) {
      const {twoTypeList} = this.data.selectOption
      let index = event.currentTarget.dataset.index
      // let type = twoTypeList[index]
      // type.check = !type.check

      twoTypeList.forEach((item, index2) => {
        if (index2 == index) {
          item.check = !item.check
        } else {
          item.check = false
        }
      })

      this.setData({
        'selectOption.twoTypeList': twoTypeList
      })
    },
    // 重置
    resetHandle() {
      const {_typeIndex, typeList} = this.data
      let twoTypeList = JSON.parse(JSON.stringify(typeList[_typeIndex].childList || []))
      this.setData({
        'selectOption.typeIndex': _typeIndex,
        'selectOption.twoTypeList': twoTypeList
      })
    },
    confirmHandle() {
      const {_typeIndex, typeList, selectOption} = this.data
      const {typeIndex, twoTypeList} = selectOption
      let type = typeList[typeIndex], type_tag = type.type_tag

      twoTypeList.forEach(item => {
        if (item.check) {
          type_tag = item.type_tag
        }
      })

      typeList[_typeIndex].childList.forEach(item => {
        item.check = false
      })

      typeList[typeIndex].childList = twoTypeList
      
      this.setData({
        open: '',
        typeList,
        _typeIndex: typeIndex,
        'params.type_belong': type.type_belong,
        'params.type_tag': type_tag
      }, () => {
        this.requestPageData(1)
      })
    },
    // 购物车调转
    shapCartHandle() {
      wx.navigateTo({
        url: '/pages/shop-cart/shop-cart',
      })
    },
    // 请求关注的门店信息
    requestMerchantList(requestData = false) {
      wx.ajax.post('findUserAllMerchant.action').then(res => {
        let merchantList = res.result || []
        let setData = { merchantList }
        let merchant_id = ''
        merchantList.forEach(item => {
          item.name = item.merchant_name
        })

        if (requestData) {
          if (merchantList.length > 0) {
            let merchant = merchantList.find(item => item.methodShop)
            merchant = merchant || merchantList[0]
  
            merchant_id =  merchant.id
            setData.merchant = merchant
            setData['params.user_merchant_id'] = merchant_id
            setData['merchant'] = merchant
          }
    
          this.setData(setData, () => {
            if (merchant_id) {
              this.requestBannerList(merchant_id)
              this.requestProductTypeTree(merchant_id)
            }
          })
        } else {
          this.setData(setData)
        }
      })
    },
    // 请求banner
    requestBannerList(merchant_id) {
      wx.ajax.post('queryMerchantBanner.action', {merchant_id}).then(res => {
        let bannerList = res.result.banner_img || []
        bannerList.forEach(item => {
          item.head_img = globalData.imageUrl + item.head_img
        })
  
        this.setData({
          refreshed: false,
          showMoreBtn: !!res.result.showMoreBtn,
          bannerList: bannerList
        })
      })
    },
    // 请求分类
    requestProductTypeTree(merchantId) {
      wx.ajax.post('queryProductTypeTree.action', {merchantId}, false).then(res => {
        let setData = {}
        let typeList = res.result.data || []
        setData.typeList = typeList
        if (typeList.length > 0) {
          let type = typeList[0]
          setData._typeIndex = 0
          setData['params.type_belong'] = type.type_belong
          setData['params.type_tag'] = type.type_tag
        }

        this.setData(setData, () => {
          this.requestPageData(1)
        })
      })
    },
    // behaviors 方法
    formatListData(data = []) {
      return data.map(item => {
        return {
          ...item,
          head_img: globalData.imageUrl + item.head_img
        }
      })
    },
    // behaviors 方法
    listPromise(data) {
      return wx.ajax.post('queryProductCenterInfoPage.action', {...data,...this.data.params}, false)
    },
    refreshHandle() {
      this.setData({
        refreshed: true
      }, () => {
        this.requestBannerList(this.data.params.user_merchant_id)
        this.requestPageData(1)
      })
    },
    lowerHandle() {
      if (this.data.curDataStatus == this.data.dataStatus.end) {
        return
      }

      this.setData({
        curLoadStatus: this.data.loadStatus.loading,
      }, () => {
        this.requestPageData()
      })
    },
    onLoad() {
      this.requestMerchantList(true)
    },
    onHide() {
      this.hide = true
    },
    onShow() {
      if (this.hide) {
        this.requestMerchantList(false)
        this.hide = false
      }

      if (!globalData.shopCart) {
        app.requestShopCart((data) => {
          this.setData({
            cartCount: data.length
          })
        })
      } else {
        this.setData({
          cartCount: globalData.shopCart.length
        })
      }
    }
  }
})